import api from '../../../api/index';
import uploadOss from '../../../utils/uploadFileOss/index';
import Toast from '@vant/weapp/toast/toast';
const defaultAvatarUrl =
	'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
const app = getApp();
Page({
	/**
   * 页面的初始数据
   */
	data: {
		userlist: null,
		defaultAvatarUrl,
		list: [
			{
				name: '我的积分',
				urlpage: '/mine/pages/myintegral/index'
			},
			{
				name: '我的设备',
				urlpage: '/mine/pages/mydevice/index'
			},
			{
				name: '地址管理',
				urlpage: '/shop/pages/deliveraddress/index'
			},
			{
				name: '联系客服',
				urlpage: '/mine/pages/contact-information/index'
			},
			{
				name: '意见反馈',
				urlpage: '/mine/pages/feedback/index'
			},
			{
				name: '用户须知',
				urlpage: '/mine/pages/serneedstoknow/index'
			},
			{
				name: '设置',
				urlpage: '/mine/pages/setup/index'
			}
		],
		tab: [
			{ name: '待付款', state: [ 'new', '待付款' ], numlength:0, url: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/mine/1.png' },
			{ name: '待发货', state: [ 'paied', '待发货' ], numlength:0, url: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/mine/2.png' },
			{ name: '待收货', state: [ 'shipped', '待收货' ], numlength:0, url: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/mine/3.png' },
			{ name: '退款/售后', state: [ 'RR', '退货退款' ], numlength:0, url: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/mine/4.png' },
			{ name: '待评价', state: [ 'completed', '已完成' ], numlength:0, url: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/mine/5.png' }
		],
		showdingdancount: false,
		mylist: 0,
		articleCount: 0,
		collectlist: 0
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// Toast.loading({
		// 	message: '加载中...',
		// 	forbidClick: true,
		// 	loadingType: 'spinner',
		//   });
		//   setTimeout(() => {
		// 	Toast.clear();
		//   },800)
		this.getuserinfo();
		this.shoporderlist(this.data.tab, 0)
	},
	goFoot() {
		wx.setStorageSync('accessToken', '');
		wx.setStorageSync('userInfo', '');
		wx.setStorageSync('LKaccessToken', '');
		wx.redirectTo({
            url: `/pages/login/qrcode`
          })
	},
	//文章收藏
	getarticleCount() {
		try {
			api.get('/api/hxhealth/favorites/count').then((res) => {
				// console.log(res);
				console.log('----res-收藏---', res);
				const array = res
				if( array.length>0 ) {
					for (let j = 0; j < array.length; j++) {
						if(array[j].kind == "article") {
							this.setData({
								articleCount: array[j].count
							});
						}
					}
				}
				this.setData({
					showcount: true
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	// 商品收藏
	shopcollectlist() {
		try {
			api.post('/api/hxhealth/goods/collectlist').then((res) => {
				// console.log(res);
				console.log('----res----', res[0]);
				this.setData({
					// collectlist: res[0]
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	getmylist() {
		// 列表
		try {
			api.post('/api/hxhealth/video/collectlist').then((res) => {
				// console.log(res);
				console.log('----res----', res[0]);
				this.setData({
					mylist: res
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	getuserinfo() {
		// 整体列表查询
		try {
			api.post('/api/hxhealth/user/load').then((res) => {
				// console.log(res);
				console.log('----res----', res[0]);
				this.setData({
					userlist: res[0]
				});
			});
		} catch (e) {
			console.error(e);
		}
	},
	goVideoPage() {
		wx.navigateTo({
			url: `/videoplayer/pages/home/index?type=true`
		});
	},
	unpay(index) {
		try {
			api.post('/api/hxhealth/shoporder/refundlist').then((res) => {
				// console.log(res);
				console.log('----res22----',index, res);
				this.setData({
					['tab[' + index + '].numlength']: res.length
				});
				// this.setData({
				// 	showdingdancount: true
				// });
				console.log(this.data.tab);
				
			});
		} catch (e) {
			console.error(e);
		}
	},
	
	// 订单列表
	shoporderlist(tab, index) {
		if (index >= tab.length-1) {
			// 递归结束条件：当index超过tab数组的长度时，结束递归
			console.log('==================待评价==================',index);
			console.log(this.data.tab);
			this.unevaluate(index)
			return;
		  } else if (index >= tab.length-2) {
			// 递归结束条件：当index超过tab数组的长度时，结束递归
			console.log('==================售后、退款==================',index);
			console.log(this.data.tab);
			this.unpay(index)
			return;
		  } else {
			const currentTab = tab[index];
		  const state = currentTab.state;
		const actions = {
			data: {
				state
			}
		}
		try {
			api.post('/api/hxhealth/shoporder/list', actions).then((res) => {
				// console.log(res);
				console.log('----res22----',index, res);
				this.setData({
					['tab[' + index + '].numlength']: res.length
				});
				console.log(this.data.tab);
				this.shoporderlist(this.data.tab, index + 1);
				
			});
		} catch (e) {
			this.shoporderlist(tab, index + 1);
			console.error(e);
		}
		  }
		  
	},
	unevaluate(index) {
		try {
			api.post('/api/hxhealth/shoporder/unevaluate').then((res) => {
				// console.log(res);
				console.log('----res22----',index, res);
				this.setData({
					['tab[' + index + '].numlength']: res.length
				});
				this.setData({
					showdingdancount: true
				});
				console.log(this.data.tab);
				
			});
		} catch (e) {
			console.error(e);
		}
	},
	goOrderPage(e) {
		const type = e.target.dataset.type
		const index = e.target.dataset.index
		console.log(type);
		console.log(index);

		wx.navigateTo({
			url: `/shop/pages/myorder/index?type=${type}&index=${index}`
		});
	},
	goNewsPage() {
		wx.navigateTo({
			url: `/mine/pages/mynews/index`
		});
	},
	onChooseAvatar(e) {
		console.log(e);
		var num = [];
		num.push(e.detail.avatarUrl);
		console.log(num);
		console.log(num);
		this.uploadDIY(num, 0, 0, 0, num.length, num);
	},
	uploadDIY(filePaths, successUp, failUp, i, length, param) {
		// 正在上传
		// debugger
		param.doing = true; // this.data.prove.doing = true;
		param.imagesUrl = [];
		let that = this;
		// wx.showLoading({
		//     title: `上传${i}/${length}张图片中`,
		//     duration: 1000
		// })

		uploadOss(filePaths[i])
			.then((res) => {
				successUp++;
				i++;
				param.imagesUrl.push(res.url);
				// that.setData({
				//     prove: that.data.prove
				// })
				if (i === length) {
					// 全部上传成功
					console.log('图片上传成功后的url', param.imagesUrl, length);
					if (successUp === length) {
						param.uploadSuccess = true;
						console.log('图片上传成功进入回调');
						// wx.hideLoading()
						that.savetmp(param.imagesUrl[0]);
					} else {
						// 图片上传部分失败
						param.doing = false;
						wx.hideLoading();
						wx.showToast({
							title: '上传图片失败,请重新上传！',
							icon: 'none',
							duration: 2000
						});
					}
				} else {
					// 递归调用uploadDIY函数
					that.uploadDIY(filePaths, successUp, failUp, i, length, param);
				}
			})
			.catch((e) => {
				console.log('---图片上传失败 catch--- e', e);
				param.doing = false;
				failUp++;
				wx.hideLoading();
				wx.showToast({
					title: '图片上传失败，请重新上传！',
					icon: 'none',
					duration: 2000
				});
			});
	},
	savetmp(e) {
		console.log(e);
		let userInfo = wx.getStorageSync('userInfo');
		userInfo.wechatimg = e;
		this.saveUserInfo(userInfo, false);
		// app.getHttpUser()
	},
	saveUserInfo(data = {}) {
		return new Promise((resolve, reject) => {
			api
				.post('/api/hxhealth/user/save', {
					data: data
				})
				.then((res) => {
					wx.showToast({
						title: '修改成功',
						icon: 'none'
					});
					this.getuserinfo();
					resolve(res);
				})
				.catch((e) => {
					reject(e);
				});
		});
	},
	// saveUserInfo() {
	//   api.post('/api/hxhealth/user/save', {
	//     data: { birthday: event }
	// }).then(() => {
	//     let userInfo = wx.getStorageSync('userInfo');
	//     userInfo.birthday = event
	//     wx.setStorageSync('userInfo', userInfo)
	//     wx.showToast({
	//         title: '修改成功',
	//         icon: 'none'
	//     })
	// }).catch(e => {
	//     console.log('error', e)
	// })
	// },
	toHealthFile() {
		wx.navigateTo({
			url: `/mine/pages/userinfo/index?titlename=个人中心`
		});
	},
	go(e) {
		console.log(e);
		const { titlename, urlpage } = e.currentTarget.dataset;
		console.log(urlpage, 'page111');
		wx.navigateTo({
			url: `${urlpage}?titlename=${titlename}`
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {
		this.shopcollectlist(); //商品收藏
		this.getarticleCount(); //文章收藏
		this.getmylist() //视频收藏
	},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
